<template>
  <div class="cleanliness-score-card">
    <!-- {{ categories }} -->
    <div class="card-header">
      <div class="icon">
        <div
          style="
            width: 24px;
            height: 24px;
            border-radius: 50%;
            border: 1px solid #ccc;
            display: flex;
            align-items: center;
            justify-content: center;
          "
        >
          <img
            style="width: 15px; height: 15px"
            :src="iconPath"
            :alt="`${headerTitle} icon`"
          />
        </div>
        <div class="icon-tooltip" v-show="showTooltip">
          {{ iconTooltip }}
        </div>
      </div>
      <div class="title">{{ headerTitle }}</div>
      <div
        @mouseenter="handleEyeMouseEnter"
        @mouseleave="handleEyeMouseLeave"
        style="cursor: pointer; position: relative; width: 18px; height: 18px"
      >
        <img
          class="eye-icon"
          src="@/assets/eye.png"
          alt=""
          style="width: 18px; height: 18px"
          @click="goDetails(headerTitle)"
        />
        <div class="eye-tooltip" v-show="showEyeTooltip">
          <div>
            Positive {{ categories.positive }} ({{ percentages.positive }}%)
          </div>
          <div>
            Neutral {{ categories.neutral }} ({{ percentages.neutral }}%)
          </div>
          <div>
            Negative {{ categories.negative }} ({{ percentages.negative }}%)
          </div>
        </div>
      </div>
    </div>

    <div class="loading-container" v-if="loading">
      <div class="loading-spinner"></div>
    </div>

    <template v-else>
      <div class="chart-container">
        <PieChart
          :option="pieChartOptions"
          style="height: 1.161rem"
          :key="chartKey"
        ></PieChart>
      </div>
      <div class="goal-info-container">
        <div class="placeholder"></div>
        <div class="goal-details">
          <div class="goal-label">Goal:</div>
          <div class="goal-value">{{ goalValue.toFixed(1) }}</div>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import { fontChart } from "@/utils/echartPxToRem";
import PieChart from "@components/common/PieChart.vue";
import defaultIcon from "@/assets/pieIcon/bigbed.png";

export default {
  components: {
    PieChart,
  },
  props: {
    headerTitle: String,
    iconPath: {
      type: String,
      default: defaultIcon,
    },
    showScoreRange: {
      type: Boolean,
      default: false,
    },
    showLegend: {
      type: Boolean,
      default: false,
    },
    categories: {
      type: Object,
      required: false,
      default: () => ({}),
    },
    goalValue: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      showEyeTooltip: false,
      eyeTooltipTimeout: null,
      loading: true,
      showTooltipTimeout: null,
      iconTooltip: "+3% from last week",
      Cleanness: "",
      showTooltip: false,
      pieChartOptions: {
        tooltip: {
          trigger: "item",
          borderColor: "#9e9e9e",
          borderWidth: 1,
          borderRadius: 4,
          padding: 8,
          textStyle: {
            color: "#454545",
            fontSize: 12,
          },
          formatter: function (params) {
            const titleStyle = "font-weight:600;font-size:12px;color:#454545;";
            const contentStyle = "font-weight:400;font-size:10px;color:#000;";

            return `
      <div style="${titleStyle}">${params.name}</div>
       <div style="${contentStyle}">&bull; ${params.value}</div>
    <div style="${contentStyle}">&bull; ${params.percent}%</div>
    `;
          },
          extraCssText: "box-shadow: 0 2px 10px rgba(0,0,0,0.1);",
        },
        legend: {
          show: this.showLegend,
          orient: "vertical",
          right: "0",
          bottom: "0%",
          itemHeight: 8,
          data: [
            { name: "check in", icon: "circle" },
            { name: "check out", icon: "circle" },
          ],
          itemGap: 1,
          textStyle: {
            padding: [0, 0, 5],
            fontSize: 10,
          },
        },
        // AllServicesHome.vue 的 data() 中，修改 pieChartOptions.graphic
        graphic: {
          type: "text",
          left: "center", // 水平居中（保留）
          top: "50%", // 垂直居中基准
          dy: 0, // 文本自身垂直居中（关键修正）
          silent: true,
          style: {
            text: this.categories?.score || 0,
            textAlign: "center", // 水平居中（保留）
            fill: "#000",
            fontSize: 18,
            fontWeight: "bold",
            // 新增：确保文本自身垂直居中
            verticalAlign: "middle",
          },
        },
        series: [
          {
            name: "Access From",
            type: "pie",
            top: "20%",
            left: "10%",
            right: "10%",
            bottom: "15%",
            radius: ["75%", "90%"],
            center: ["50%", "50%"],
            avoidLabelOverlap: false,
            minAngle: 1, // 设置最小角度为1度，避免小比例扇形被隐藏
            padAngle: 0,
            silent: true,
            itemStyle: {
              borderColor: "#fff",
              borderWidth: 2, // 适当减小边框宽度
              borderRadius: 10, // 相应减小圆角
            },
            label: {
              show: true,
              formatter: function (params) {
                // 去掉小数，直接取整
                return Math.round(params.percent) + "%";
              },
              position: "outside",
              padding: [-30, -30],
              minAngle: 1, // 最小角度，小于这个值的不显示标签
              minShowLabelAngle: 1, // 设置为1度，很小的角度也会显示标签
              textStyle: {
                fontSize: 12,
                fontWeight: "normal",
              },
            },
            labelLine: {
              show: false,
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: "bold",
              },
            },
            data: [
              {
                value: Math.max(this.categories?.positive || 0.01, 0.01),
                itemStyle: { color: "#2FAA68" },
                name: "Positive Reviews",
              },
              {
                value: Math.max(this.categories?.neutral || 0.01, 0.01),
                itemStyle: { color: "#EFB82C" },
                name: "Neutral Reviews",
              },
              {
                value: Math.max(this.categories?.negative || 0.01, 0.01), // 确保最小值0.01
                itemStyle: { color: "#CE4049" },
                name: "Negative Reviews",
              },
            ],
          },
        ],
        // media: [
        //   {
        //     // 当屏幕宽度≤1150px时生效
        //     query: {
        //       maxWidth: 1150,
        //     },
        //     option: {
        //       legend: {
        //         show: false, // 缩小后的图例间距
        //       },
        //       series: [
        //         {
        //           label: {
        //             show: false, // 关闭内部标签显示
        //           },
        //         },
        //       ],
        //     },
        //   },
        // ],
      },
      updateMarker: 0,
      chartKey: 0, // 用于触发组件重新渲染的键
      isUpdating: false, // 更新状态标记
    };
  },
  methods: {
    handleEyeMouseEnter() {
      clearTimeout(this.eyeTooltipTimeout);
      this.eyeTooltipTimeout = setTimeout(() => {
        this.showEyeTooltip = true;
      }, 300);
    },
    handleEyeMouseLeave() {
      clearTimeout(this.eyeTooltipTimeout);
      this.showEyeTooltip = false;
    },
    goDetails(headerTitle) {
      console.log("实际传递的标题:", headerTitle); // 添加调试日志
      this.$emit("clickTitle", headerTitle);
    },

    handleMouseEnter() {
      clearTimeout(this.showTooltipTimeout);
      this.showTooltipTimeout = setTimeout(() => {
        this.showTooltip = true;
      }, 300);
    },
    handleMouseLeave() {
      clearTimeout(this.showTooltipTimeout);
      this.showTooltip = false;
    },

    // 强制更新图表方法
    forceUpdateChart() {
      this.isUpdating = true;
      this.updateMarker++;

      // 添加轻微的缩放动画
      const chartContainer = this.$refs.chartContainer;
      if (chartContainer) {
        chartContainer.style.transform = "scale(1.05)";
        chartContainer.style.transition = "transform 0.3s ease";

        this.$nextTick(() => {
          chartContainer.style.transform = "scale(1)";
          this.isUpdating = false;
        });
      } else {
        this.$nextTick(() => {
          this.isUpdating = false;
        });
      }
    },

    // 触发图表重新渲染
    triggerChartRefresh() {
      this.chartKey++; // 更改key值强制重新渲染组件
    },
  },
  mounted() {
    // console.log("子组件接收到的categories:", this.categories, 333333);
  },
  computed: {
    percentages() {
      const total =
        (this.categories.positive || 0) +
        (this.categories.neutral || 0) +
        (this.categories.negative || 0);
      return {
        positive: total
          ? Math.round((this.categories.positive / total) * 100)
          : 0,
        neutral: total
          ? Math.round((this.categories.neutral / total) * 100)
          : 0,
        negative: total
          ? Math.round((this.categories.negative / total) * 100)
          : 0,
      };
    },
  },
  watch: {
    categories: {
      handler(newVal) {
        if (newVal && Object.keys(newVal).length > 0) {
          this.loading = false;

          const oldData = this.pieChartOptions.series[0].data;
          const newData = [
            {
              value: newVal.positive,
              itemStyle: { color: "#2FAA68" },
              name: "Positive Reviews",
            },
            {
              value: newVal.neutral,
              itemStyle: { color: "#EFB82C" },
              name: "Neutral Reviews",
            },

            {
              value: newVal.negative,
              itemStyle: { color: "#CE4049" },
              name: "Negative Reviews",
            },
          ];

          const dataChanged = !oldData.every((oldItem, index) => {
            return (
              oldItem.value === newData[index].value &&
              oldItem.itemStyle.color === newData[index].itemStyle.color &&
              oldItem.name === newData[index].name
            );
          });

          this.pieChartOptions.series[0].data = newData;
          this.pieChartOptions.graphic.style.text = newVal.score || 0;

          // 无论数据是否变化，都触发更新效果
          this.forceUpdateChart();
          this.triggerChartRefresh();
        } else {
          this.loading = true;
        }
      },
      immediate: true,
      deep: true,
    },
  },
};
</script>

<style scoped lang="scss">
.eye-tooltip {
  position: absolute;
  top: 100%;
  left: calc(50% - 55px);
  transform: translateX(-50%);
  margin-top: 8px;
  padding: 8px;
  font-size: 12px;
  color: #000;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  opacity: 0;
  transition: opacity 0.2s ease;
  min-width: 150px; /* 确保最小宽度 */
  text-align: left;

  div {
    margin: 3px 0;
    display: flex;
    align-items: center;

    &:before {
      content: "";
      display: inline-block;
      width: 8px;
      height: 8px;
      border-radius: 50%;
      margin-right: 6px;
    }

    &:first-child:before {
      background: #2faa68;
    }
    &:nth-child(2):before {
      background: #efb82c;
    }
    &:last-child:before {
      background: #ce4049;
    }
  }
}

div:hover .eye-tooltip {
  opacity: 1;
}
// 替换原来的 ::v-deep 规则
:deep(.cleanliness-score-card) .card-header img.eye-icon {
  width: 16px;
  height: 16px;
  cursor: pointer;
  padding: 6px;
  box-sizing: content-box;
  border: 2px solid transparent;
  transition: all 0.3s ease;

  &:hover {
    background: red !important;
    opacity: 0.8 !important;
    transform: scale(1.2);
    border-color: white !important;
  }
}
.cleanliness-score-card .card-header img:hover {
  // background: red !important;
  opacity: 0.8 !important;
  // transform: scale(1.2);
  border-color: white !important;
}

.cleanliness-score-card {
  position: relative;
  padding: 6px 13px 6px 14px;
  display: flex;
  height: 100%;
  flex-direction: column;
  justify-content: space-between;
  box-sizing: border-box;
  min-height: 0;
  border-radius: 20px;

  .card-header {
    display: flex;
    align-items: center;
    min-width: 0;

    .icon-wrapper {
      display: flex;
      flex-shrink: 0;
      align-items: center;
      justify-content: center;
      width: 24px;
      height: 24px;
      border: 1px solid #cdcccc;
      text-align: center;
      background: #fff;
      border-radius: 50%;

      .icon {
        width: 0.1667rem;
        height: 0.1667rem;

        img {
          width: 100%;
          height: 100%;
          object-fit: contain;
        }
      }
    }

    .title {
      flex: 1;
      min-width: 0;
      margin-left: 0.0556rem;
      overflow: hidden;
      font-size: 0.0694rem;
      font-weight: 600;
      color: #6a6969;
    }
  }

  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;

    .loading-spinner {
      width: 30px;
      height: 30px;
      border: 3px solid #f3f3f3;
      border-top: 3px solid #3498db;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }
  }

  .chart-container {
    position: absolute;
    top: 60%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100%;
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: start;
    padding-bottom: 10px;
    flex: 1;
    will-change: transform;
  }

  .goal-info-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .goal-details {
      display: flex;
      align-items: center;
      .goal-label {
        font-size: 0.0694rem;
        font-weight: 600;
        color: #155c96;
      }
      .goal-value {
        margin-left: 5px;
        font-size: 0.0694rem;
        font-weight: 600;
        color: #6a6969;
      }
    }
  }

  .icon {
    position: relative;
    img {
      width: 24px;
      height: 24px;
    }
    .icon-tooltip {
      position: absolute;
      bottom: -20;
      left: 50%;
      margin-bottom: 8px;
      padding: 6px 8px;
      font-size: 10px;
      color: #fff;
      font-size: 12px;
      font-weight: 400;
      background: #454343;
      border-radius: 4px;
      white-space: nowrap;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      z-index: 1000;
      opacity: 0;
      transition: opacity 0.2s ease;
    }

    &:hover .icon-tooltip {
      opacity: 1;
    }
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
